'use strict';
const dbHelper = require("db-helper")
const uniID = require("uni-id")
const fs = require("fs")
const images = require("images")
const {
	CLOUDURL
} = require('config')

const downloadImg = async (url, filePath) => {
	return new Promise(async (resolve, reject) => {
		try {
			// console.log("下载", url);
			let res = await uniCloud.httpclient.request(url);
			resolve(res.data);
		} catch (e) {
			reject(e);
		}
	})
}
exports.main = async (event, context) => {
	console.log('优享商品海报');
	//event为客户端上传的参数
	let {
		goodsId,
		skuId,
		shareManId,
		queryStringParameters
	} = event;
	if (!goodsId && queryStringParameters) {
		goodsId = queryStringParameters.goodsId;
	}
	if (!skuId && queryStringParameters) {
		skuId = queryStringParameters.skuId;
	}
	if (!shareManId && queryStringParameters) {
		shareManId = queryStringParameters.shareManId;
	}
	if (!goodsId) {
		return {
			code: 500,
			msg: "参数错误"
		}
	}
	try {
		let goods = await dbHelper.getById("t3ds-mall-goods", goodsId);
		if (!goods) {
			return {
				code: 500,
				msg: "商品不存在"
			}
		}
		if (!goods.share_poster) {
			return {
				code: 500,
				msg: "商品没配置海报"
			}
		}
		let t = ['goods-poster', goodsId]
		let userRes = null
		if (shareManId) {
			t.push(shareManId)
			userRes = await dbHelper.getOne("uni-id-users", {
				id: Number(shareManId)
			})
		}
		if (skuId) {
			t.push(skuId)
		}
		let fileName = `${t.join('_')}.jpg`
		let cache = await dbHelper.getOne("file-cache", {
			srcUrl: fileName
		})
		console.log("cache: ", cache);
		if (cache) {
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': `${cache.cachedUrl}?_t=${Date.now()}`
				}
			}
		}
		let queryParams = [`goodsId=${goodsId}@`]
		if (shareManId) {
			queryParams.push(`shareManId=${shareManId}@`)
		}
		if (skuId) {
			queryParams.push(`skuId=${skuId}@`)
		}
		// 二维码
		let text = encodeURIComponent(
			`https://test.the3dspace.cn/platform-goods-detail?${queryParams.join('&')}`);
		let qrcodeBuff = await downloadImg(`${CLOUDURL}/genQRCode?text=${text}`);
		let qrcodeImgSize = 244;
		let qrcodeImg = images(qrcodeBuff).resize(qrcodeImgSize, qrcodeImgSize);
		let posterBuff = await downloadImg(`${goods.share_poster}?_t=${Date.now()}`);
		let posterImg = await images(posterBuff);
		let qrcodeImgX = posterImg.width() - qrcodeImgSize - 20;
		let qrcodeImgY = posterImg.height() - qrcodeImgSize - 20;
		let combined = posterImg.draw(qrcodeImg, qrcodeImgX, qrcodeImgY).encode("jpg", {
			operation: 50
		});

		if (userRes && userRes.avatar) {
			let avatarBuff = await downloadImg(userRes.avatar);
			let avatarImg = images(avatarBuff).resize(qrcodeImgSize / 5);
			let avatarImgX = qrcodeImgX + qrcodeImg.width() / 2 - avatarImg.width() / 2;
			let avatarImgY = qrcodeImgY + qrcodeImg.height() / 2 - avatarImg.height() / 2;
			combined = posterImg.draw(avatarImg, avatarImgX, avatarImgY).encode("jpg", {
				operation: 50
			});
		}

		let res = await uniCloud.uploadFile({
			cloudPath: "fileCache/" + fileName,
			fileContent: combined
		})
		let {
			fileID
		} = res
		if (uniCloud.$provider == 'aliyun') {
			await dbHelper.insert("file-cache", {
				srcUrl: fileName,
				cachedUrl: fileID,
				fileID: fileID
			})
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': `${fileID}?_t=${Date.now()}`
				}
			}
		} else {
			res = await uniCloud.getTempFileURL({
				fileList: [fileID]
			})
			let {
				fileList
			} = res
			await dbHelper.insert("file-cache", {
				srcUrl: fileName,
				cachedUrl: fileList[0].download_url,
				fileID: fileID
			})

			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': `${fileList[0].download_url}?_t=${Date.now()}`
				}
			}
		}
	} catch (e) {
		console.log("获取商品海报遇到错误", e);
		return {
			code: 500,
			msg: e.message
		}
	}
};
